package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.PermissionAnnotation;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper mapper;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;



    @Override
    public PageInfo<Permission> getPageInfo(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> list = mapper.getList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void reload() {

        List<Permission> permissions = mapper.selectAll();

        Set<String> set = new HashSet<>();
        for (Permission permission : permissions){
            String expression = permission.getExpression();
            set.add(expression);
        }

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        //获取每个controller方法
        for (HandlerMethod method : values){
            //拿到贴注解的方法
            PermissionAnnotation methodAnnotation = method.getMethodAnnotation(PermissionAnnotation.class);
           //判空
            if (methodAnnotation!=null){
                //获取表达式
                String expression = methodAnnotation.expression();
                //若内存不包含贴了注解的方法
                if (!set.contains(methodAnnotation.expression())){
                     Permission permission  = new Permission();
                    permission.setName(methodAnnotation.name());
                    permission.setExpression(methodAnnotation.expression());
                    mapper.insert(permission);
                }

            }

        }

    }

    @Override
    public List<Permission> getAll() {
        return mapper.selectAll();
    }
}
